<template>
  <view class="add-addr">
    <view class="increaseAddress">
      <uni-forms
        :modelValue="addressData"
        class="userData"
        ref="form"
        :rules="rules"
      >
        <uni-forms-item label="联系人" required name="userName">
          <uni-easyinput
            type="text"
            v-model="addressData.userName"
            placeholder="请输入姓名"
          />
        </uni-forms-item>
        <uni-forms-item
          type="number"
          required
          name="telNumber"
          label="手机号码"
        >
          <uni-easyinput
            v-model="addressData.telNumber"
            placeholder="请输入手机号码"
          />
        </uni-forms-item>
        <uni-forms-item label="详细地址" required name="allName">
          <uni-easyinput
            :disabled="true"
            placeholder="点击选择"
            v-model="addressData.allName"
          />
          <view class="abs_view" @click="chooseAddr"> </view>
        </uni-forms-item>
        <uni-forms-item label="门牌号" required name="detailInfo">
          <uni-easyinput
            type="text"
            v-model="addressData.detailInfo"
            placeholder="请输入门牌号"
          />
        </uni-forms-item>
      </uni-forms>
      <button class="submit-btn" @click="submitForm">确定</button>
    </view>
  </view>
</template>

<script>
import { chooseLocation } from "../../utils/address.js"
import { isPhone, isName, showToast } from "../../utils/util"
import { setStorage, getStorage } from "../../api/Storage"
export default {
  data() {
    return {
      type: "add",
      addressData: {
        userName: "",
        telNumber: "",
        detailInfo: "",
        nationalCode: 510000,
        allName: "",
      },
      rules: {
        // 对userName字段进行必填验证
        userName: {
          rules: [
            {
              required: true,
              errorMessage: "请输入正确姓名",
            },
            {
              minLength: 2,
              maxLength: 5,
              errorMessage: "姓名长度在 {minLength} 到 {maxLength} 个字符",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                const flagName = isName(value)
                if (!flagName) {
                  callback("请输入正确姓名")
                }
                return flagName
              },
            },
          ],
        },
        telNumber: {
          rules: [
            {
              required: true,
              errorMessage: "请输入正确手机号",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                const flagPhone = isPhone(value.trim())
                if (!flagPhone) {
                  callback("请输入正确手机号")
                }
                return flagPhone
              },
            },
          ],
        },
        allName: {
          rules: [
            {
              required: true,
              errorMessage: "请选择详细地址",
            },
          ],
        },
        detailInfo: {
          rules: [
            {
              required: true,
              errorMessage: "请输入门牌号",
            },
          ],
        },
      },
    }
  },
  onLoad(options) {
    this.type = options.type
    if (this.type !== "add") {
      let item = JSON.parse(decodeURIComponent(options.item))
      this.addressData = item
      console.log(item)
    }
    console.log(this.type)
  },
  onReady() {
    // 需要在onReady中设置规则
    this.$refs.form.setRules(this.rules)
  },

  methods: {
    chooseAddr() {
      chooseLocation().then((res) => {
        this.addressData.allName = res.address
      })
    },

    submitForm() {
      this.$refs.form
        .validate()
        .then(() => {
          let { addressData } = this
          let addressList = getStorage("addressList") || []
          if (this.type === "add") {
            addressData.id = new Date().getTime()
            if (addressList.length === 0) {
              addressData.type = 1
            } else {
              const index = addressList.findIndex((v) => v.type === 1)
              if (index > -1) {
                addressData.type = 0
              } else {
                addressData.type = 1
              }
            }
            addressList.push(addressData)
          } else {
            addressList.forEach((v) => {
              if (v.id === addressData.id) {
                v.userName = addressData.userName
                v.telNumber = addressData.telNumber
                v.detailInfo = addressData.detailInfo
                v.allName = addressData.allName
              }
            })
          }
          setStorage("addressList", addressList)
          showToast({
            title: this.type === "edit" ? "修改成功" : "添加成功",
            icon: "success",
          })
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            })
          }, 1500)
        })
        .catch((err) => {
          console.log("表单错误信息：", err)
        })
    },
  },
}
</script>

<style lang="scss">
.add-addr {
  .abs_view {
    position: absolute;
    left: 0;
    top: 0;
    width: 670upx;
    height: 100%;
    background: rgba(0, 0, 0, 0);
    z-index: 3000;
  }

  .submit-btn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100upx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #1182e8;
    font-size: 32upx;
    color: #fff;
    border-radius: 0;
  }

  .iconfont {
    color: #333;
    font-size: 40upx;
    display: inline-block;
    width: 40upx !important;
    height: 40upx;
  }

  .right {
    position: absolute;
    right: 0;
    z-index: 9;
  }

  .title {
    background-color: #37384c;
    color: #fff;
    font-size: 32upx;
    padding: 0 40upx;
    line-height: 80upx;
    box-shadow: 0upx 6upx 12upx #dbe7ff;
  }

  .userData {
    box-shadow: 0upx 6upx 12upx #dedede;
    width: 100%;
    border-radius: 0 0 16upx 16upx;
    background-color: #fff;
    padding: 40upx;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    box-sizing: border-box;
  }

  .userItem {
    width: 100%;
    height: 110upx;
    display: flex;
    align-items: center;
    border-bottom: 2upx solid #ccc;
    font-size: 26upx;
    color: #333;
    position: relative;

    view {
      width: 150upx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    input {
      flex: 1;
    }
  }

  /* 面积 */
  .area {
    box-sizing: content-box;
    box-shadow: 0upx 6upx 12upx #dedede;
    width: 626upx;
    height: 188upx;
    border-radius: 16upx;
    background-color: #fff;
    padding: 40upx 40upx;
    margin-top: 20upx;
  }

  .areaTitle {
    font-size: 26upx;
    color: #333;
    padding-bottom: 36upx;
  }

  .areaCon {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
  }

  .areaItem {
    background: #ffffff;
    border: 1px solid #ccc;
    width: 142upx;
    height: 44upx;
    text-align: center;
    line-height: 44upx;
    font-size: 24upx;
    color: #333;
    border-radius: 22upx;
    margin-bottom: 30upx;
    margin-right: 48upx;
  }

  /* 动态类 */
  .areaText {
    background-color: #1182e8;
    color: #fff;
  }

  /* 保存 */
  .save {
    width: 294upx;
    height: 82upx;
    text-align: center;
    line-height: 82upx;
    background-color: #1182e8;
    border-radius: 50upx;
    font-size: 40upx;
    color: #fff;
    margin: 40upx auto 0;
    box-shadow: -4upx -6upx 12upx #dedede;
  }
}
</style>
